let http = require('http');
let crypto = require('crypto');
const { spawn } = require('child_process');
let server = http.createServer(function (req, res) {
    console.log(req.method, req.url);
    if (req.method == 'POST' && req.url == '/webhook') {
        let buffers = [];
        req.on('data', function (chunk) {
            buffers.push(chunk);
        });
        req.on('end', function () {
            let body = Buffer.concat(buffers);
            console.log(req.headers);
            let event = req.headers['x-gitee-event']//event=push
            //gitee请求来的时候，要传递请求体body，另外还会传一个token过来，你需要验证token对不对
            let signature = req.headers['x-gitee-token'];
            //这个秘钥需要和我们gitee那里要一样
            let secret = '123456';
            //把请求体转成sha1
            let sha1 ='sha1='+ crypto.createHmac('sha1', secret).update(body).digest('hex');
            console.log(sha1,'sha1');
            console.log(signature,'signature');
            //如果和我们的signature一样，那就成功，不一样，就失败
            if (secret !== signature) {
                console.log('验证失败');
            }
            res.setHeader('Content-Type', 'application/json');
            res.end(JSON.stringify({
                ok: true
            }))
            console.log('event',event);
            if (event == 'Push Hook') {//开始部署
                let payload = JSON.parse(body);
                console.log('我是payload',payload.repository.name);
                let child = spawn('sh',[`./${payload.repository.name}.sh`]);
                let buffers = [];
                child.stdout.on('data', function (chunk) {
                    buffers.push(chunk);
                });
                child.stdout.on('end', function () {
                    let log = Buffer.concat(buffers);
                    console.log(log);
                })
            }
        })

    } else {
        res.end('Not Found')
    }
})
server.listen(3004, () => {
    console.log('webHooks服务已经在3004端口上启动');
})